<template>
  <el-select
    v-model="selectedId"
    :placeholder="placeholder"
    clearable
    @change="handleChange"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { departmentApi } from '@/api/departmentApi'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择部门'
  }
})

const emit = defineEmits(['update:modelValue', 'select'])

const selectedId = ref(props.modelValue)
const options = ref([])

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  selectedId.value = newVal
})

// 监听选择变化
const handleChange = (value) => {
  emit('update:modelValue', value)
  const selected = options.value.find(item => item.id === value)
  if (selected) {
    emit('select', selected)
  }
}

// 加载部门列表
const loadDepartments = async () => {
  try {
    const res = await departmentApi.getDepartmentTree()
    if (res.code === 200) {
      // 将树形结构扁平化为列表
      const flattenDepts = (depts, prefix = '') => {
        let result = []
        depts.forEach(dept => {
          result.push({
            id: dept.id,
            name: prefix + dept.name
          })
          if (dept.children?.length) {
            result = result.concat(flattenDepts(dept.children, prefix + '/' + dept.name + '/'))
          }
        })
        return result
      }
      options.value = flattenDepts(res.data)
    }
  } catch (error) {
    console.error('加载部门列表失败:', error)
    ElMessage.error('加载部门列表失败')
  }
}

onMounted(() => {
  loadDepartments()
})
</script> 